package com.frinder.official.akka.actors;

import akka.actor.AbstractActor;
import akka.actor.ReceiveTimeout;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;

/**
 * Created by frinder on 2017/9/13.
 * <p>
 * 注：更新 ReceiveTimeout 的实例
 */
@Component
@Scope("prototype")
public class ReceiveTimeoutActor extends AbstractActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

    public ReceiveTimeoutActor() {
        // To set an initial delay
        getContext().setReceiveTimeout(Duration.create(10, TimeUnit.SECONDS));
        log.debug("ReceiveTimeout : {}", getContext().receiveTimeout());
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .matchEquals("Hello", s -> {
                    // To set in a response to a message
                    getContext().setReceiveTimeout(Duration.create(1, TimeUnit.SECONDS));
                    log.debug("ReceiveTimeout : {}", getContext().receiveTimeout());
                })
                .match(ReceiveTimeout.class, r -> {
                    // To turn it off
                    getContext().setReceiveTimeout(Duration.Undefined());
                    log.debug("ReceiveTimeout : {}", getContext().receiveTimeout());
                })
                .build();
    }
}